<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

$MTF = JFX::registry('ThirdParty_MTF');
$BWT = JFX::registry('ThirdParty_BWT');


$updates = array();
$conns = array();

$subs = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_subscriptions");

foreach($subs as $k=>$v){
    if(!array_key_exists($v['connection_id'], $conns)){
        $connData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_servers WHERE id = '{$v['connection_id']}'");
        $conns[$connData['id']] = $connData;
        if(!$VMC->connect($connData['id'])){
            JFX::addError('Could not connect to '.$this->getContentLang('conn_title', $connData['id']));
            continue;
        }
    }

    $curVersion = $VM->getCurrentVersion($v['package_id']);

    $res = $VMC->request($connData['id'], $connData['url'].'/get-next-version/', array('keyname'=>$v['keyname'], 'current_version'=>$curVersion));

    $res = unserialize($res);
    if(!is_object($res) || $res->result === 'FAIL'){
        JFX::addError('Failed to retrieve version udpate for '.$v['keyname'].' on '.$this->getContentLang('conn_title', $connData['id']).'. Reason: '.$res->reason);
        continue;
    }

    if($res->version === $curVersion) continue;

    if($VM->isLaterVersion($res->version, $curVersion)){
        // add another update
        $vRes = $VMC->request($connData['id'], $connData['url'].'/get-version-details/', array('version'=>$res->version, 'keyname'=>$v['keyname']));
        $vRes = unserialize($vRes);
        if(!is_object($vRes) || $vRes->result === 'FAIL'){
            JFX::addError('Failed to retrieve version details for '.$v['keyname'].' version '.$res->version.' using '.$this->getContentLang('conn_title', $connData['id']));
            continue;
        }

        $fRes = $VMC->request($connData['id'], $connData['url'].'/get-num-changed-files/', array('version'=>$res->version, 'keyname'=>$v['keyname']));
        $fRes = unserialize($fRes);
        if(!is_object($fRes) || $fRes->result === 'FAIL'){
            JFX::addError('Failed to retrieve number of changed files for '.$v['keyname'].' version '.$res->version.' using '.$this->getContentLang('conn_title', $connData['id']));
            continue;
        }


        $updateParams = array(
            'connection_id' => $connData['id'],
            'connection_title' => $this->getContentLang('conn_title', $connData['id']),
            'keyname' => $v['keyname'],
            'version' => $res->version,
            'previous_version' => $curVersion,
            'num_files' => $fRes->num_changed_files,
            'change_log' => $vRes->change_log,
            'cData' => $connData,
            'sData' => $v
        );

        $updates[] = $updateParams;

    }

}









if(get('upgrade')==1){

    if($CONFIG->lockUpdates){
        JFX::addError('Forbidden to upgrade on this system');
        JFX::redirect($this->adminUrl.'/updates');
    }

    $packageid = (int) get('package');
    $pData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_packages WHERE id = '{$packageid}'");

    $curVersion = $pData['current_version'];
    $vData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_versions WHERE package_id = '{$pData['id']}' AND previous_version = '{$curVersion}'");
    if(is_array($vData) && count($vData)>0){
        // can upgrade!
        eval('$basePath = "'.$pData['base_path'].'";');
        $folders = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_files WHERE package_id = '{$pData['id']}' AND version_id = '{$vData['id']}' AND file_type = 0 ORDER BY filename ASC");

        foreach($folders as $k=>$v){
            if(!is_dir($basePath.'/'.$v['filename'])){
                // file does not exists
                if($v['update_action']==2 || $v['update_action']==1){
                    // create the folder
                    mkdir($basePath.'/'.$v['filename']);
                }
            }else{
                // folder exists
                if($v['update_action']==3){
                    unlink_directory($basePath.'/'.$v['filename']);
                }
            }
        }

        $files = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_files WHERE package_id = '{$pData['id']}' AND version_id = '{$vData['id']}' AND file_type = '1' ORDER BY filename ASC");

        foreach($files as $k=>$v){
            if($v['file_type'] == 1 && !file_exists($this->dirname.'/files/'.$v['id'].'.vmsf')) continue;

            if(!is_dir($basePath.'/'.$v['filename'])){
                // file does not exists
                if($v['update_action']==2 || $v['update_action']==1){
                    // create the file
                    $fh = fopen($basePath.'/'.$v['filename'], 'w');
                    fwrite($fh, file_get_contents($this->dirname.'/files/'.$v['id'].'.vmsf'));
                    fclose($fh);
                }
            }else{
                // file exists
                if($v['update_action']==3){
                    // delete it
                    unlink($basePath.'/'.$v['filename']);
                }else if($v['update_action']==1 || $v['update_action']==2){
                    // update the file
                    $fh = fopen($basePath.'/'.$v['filename'], 'w');
                    fwrite($fh, file_get_contents($this->dirname.'/files/'.$v['id'].'.vmsf'));
                    fclose($fh);
                }
            }
        }

        $DB->update($CONFIG->dbprefix.'vms_packages', array('current_version' => $vData['version']), "id = '{$packageid}'");

        eval($vData['eval_code']);

        JFX::addSuccess('Upgrade successful!');
        JFX::redirect($this->adminUrl.'/updates');

    }

}














if(get('update')==1){
    // wanting to download and install updates
    foreach($updates as $k=>$v){
        if($v['connection_id']==get('conn') && $v['keyname']==get('keyname') && $v['version']==get('version')){
            // bingo!
            $version = get('version');
            $prevVersion = get('prevVersion');

            $fRes = $VMC->request($connData['id'], $connData['url'].'/get-files/', array('version'=>$version, 'keyname'=>$v['keyname']));
            $fRes = unserialize($fRes);



            if(!is_object($fRes) || $fRes->result === 'FAIL'){
                JFX::addError($fRes->result.': Failed to retrieve changed files for '.$v['keyname'].' version '.$version.' using '.$this->getContentLang('conn_title', get('conn')));
                JFX::redirect($this->adminUrl.'/updates/');
            }

            $vRes = $VMC->request($connData['id'], $connData['url'].'/get-version-details/', array('version'=>$version, 'keyname'=>$v['keyname']));
            $vRes = unserialize($vRes);
            if(!is_object($vRes) || $vRes->result === 'FAIL'){
                JFX::addError('Failed to retrieve version details for '.$v['keyname'].' version '.$version.' using '.$this->getContentLang('conn_title', get('conn')));
                JFX::redirect($this->adminUrl.'/updates/');
            }

            $keyname = $DB->escape(get('keyname'));
            $packageid = $DB->oneValue($CONFIG->dbprefix.'vms_packages', 'id', "keyname = '{$keyname}'");

            $vData = array(
                'package_id' => $packageid,
                'version' => $version,
                'previous_version' => $vRes->vData->previous_version,
                'eval_code' => $vRes->vData->eval_code,
                'change_log' => $vRes->vData->change_log
            );
            $versionid = $DB->insert($CONFIG->dbprefix.'vms_versions', $vData);


            foreach($fRes->files as $k2=>$fData){
                $dbParams = array(
                    'package_id' => $packageid,
                    'version_id' => $versionid,
                    'filename' => $fData['filename'],
                    'file_type' => $fData['file_type'],
                    'update_action' => $fData['update_action']
                );
                $fileid = $DB->insert($CONFIG->dbprefix.'vms_files', $dbParams);


                if($fData['file_type']==1){
                    $fileContents = $FCRYPT->decrypt($fData['file_contents']);

                    if(file_exists($this->dirname.'/files/'.$fileid.'.vmsf')) unlink($this->dirname.'/files/'.$fileid.'.vmsf');
                    $fh = fopen($this->dirname.'/files/'.$fileid.'.vmsf', 'w');
                    fwrite($fh, $fileContents);
                    fclose($fh);

                }
            }

        }
    }
    JFX::addSuccess('Import success');
    JFX::redirect($this->adminUrl.'/updates');
}







$upgrades = array();

$packages = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_packages ORDER BY keyname ASC");
foreach($packages as $k=>$v){
    $curVersion = $v['current_version'];
    $ugData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_versions WHERE package_id = '{$v['id']}' AND previous_version = '{$curVersion}'");
    if(is_array($ugData) && count($ugData)>0){
        // can upgrade!
        $upgrades[] = array(
            'package_id' => $v['id'],
            'keyname' => $v['keyname'],
            'previous_version' => $curVersion,
            'version' => $ugData['version']
        );

    }
}


















$SMARTY->assign('updates', $updates);
$SMARTY->assign('upgrades', $upgrades);

echo $this->fetchTemplate('updates.tpl');


























